<?php
declare(strict_types=1);

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * 访问 http://localhost:8080/hello/world 输出 {"name":"world"}
 */

$app->get('/hello/{name}', function ($name, ServerRequestInterface $request, ResponseInterface $response): ResponseInterface {
    // $response->getBody()->write('Hello!');
    error_log('-----body: ' . $response->getBody()->__tostring());
    $response->getBody()->write(json_encode(['name' => $name]));
    return $response;
});
$app->get('/', function (ServerRequestInterface $request, ResponseInterface $response): ResponseInterface {
    // $response->getBody()->write('Hello!');
    error_log('-----body: ' . $response->getBody()->__tostring());
    $response->getBody()->write(json_encode(['success' => "ok"]));
    return $response;
});

$app->add(function (ServerRequestInterface $request, RequestHandlerInterface $handler) use ($app): ResponseInterface {
    $response = $app->getResponseFactory()->createResponse();
    // $response->getBody()->write(json_encode(['request' => $request->getUri()->getPath()]));
    // echo json_encode(['request' => $request->getUri()->getPath()]);
    // return $response; // 直接结束
    return $handler->handle($request); // 处理下一个中间件, 同时可以进入请求
});